package com.cropdoctor.config.handler;

import com.cropdoctor.model.po.SysPermissionPo;
import com.cropdoctor.service.SysPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;


/*
 * @description: 查询接口所配置的权限
 * 拦截到当前的请求，并根据请求路径从数据库中查出当前资源路径需要哪些权限才能访问，然后将查出的需要的权限列表交给AccessDecisionManager去处理后续逻辑
*/

@Component
public class CustomizeFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    SysPermissionService sysPermissionService;



    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        //获取请求地址
        String requestUrl = ((FilterInvocation) o).getRequestUrl();
        List<ConfigAttribute> list = null;
        if(requestUrl != null) {
            if(requestUrl.contains("?")) requestUrl = requestUrl.substring(0,requestUrl.indexOf("?"));
            String[] split = requestUrl.split("/");
            String path = "";
            if(split.length > 1) path = split[1];

            //查询具体某个具体接口路径的权限
            List<SysPermissionPo> permissionList =  sysPermissionService.selectListByPath("/"+path);
            if(permissionList == null || permissionList.size() == 0){
                //请求路径没有配置权限，表明该请求接口可以任意访问
                return null;
            }
            String[] attributes = new String[permissionList.size()];
            for(int i = 0;i<permissionList.size();i++){
                attributes[i] = permissionList.get(i).getPermissionCode(); //把权限code封装进去
            }
            list = SecurityConfig.createList(attributes);
        }
        return list;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}

